package com.example.demo.utils;

import com.example.demo.domain.dao.OptionalCourse;
import com.example.demo.domain.dto.Classroom;
import com.example.demo.exception.NotSupportException;
import com.example.demo.mapper.ManagerDao;
import com.example.demo.domain.dto.ClassInfo;
import com.example.demo.domain.result.helper.Course;
import com.example.demo.domain.result.helper.Time;
import com.example.demo.domain.result.ScheduleResult;
import com.example.demo.domain.result.StudentInfo;
import com.example.demo.domain.dto.TimeAndPlaceList;
import com.example.demo.exception.PasswordErrorException;
import com.google.gson.Gson;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 解析爬虫获取的数据工具类
 *
 * @author lizijian
 */
@Slf4j
@Component
public class ParseUtil {


  private static ManagerDao managerDao;

  private static final Gson GSON = new Gson();

  @Autowired
  public void setManagerDao(ManagerDao managerDao) {
    ParseUtil.managerDao = managerDao;
  }

  /**
   * 获取班级课表
   *
   * @param className 班级名
   * @return 课程列表
   * @throws PasswordErrorException 密码错误
   */
  public static ArrayList<Course> getClassSchedule(String className)
      throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getClassScheduleDoc(className);
    System.out.println(document.title());
    Elements tr = document.select("tr");
    ArrayList<Course> courseList = new ArrayList<>(20);
    int time = 0;
    //time表示节段 time=1表示第1-2节
    for (Element element : tr) {
      if (time >= 1 && time <= 5) {
        Elements td = element.select("td");
        String[] day = String.valueOf(td).split("\n");
        //d表示周几
        for (int d = 0; d < day.length; d++) {
          if (day[d].contains("<br><br>")) {
            day[d] = day[d].substring(5, day[d].length() - 6);
            String[] singleCourse = day[d].split("<br><br>");
            for (String course : singleCourse) {
              String[] singleBr = course.split("<br>");
              Course course1 = new Course();
              Time time1 = new Time();
              time1.setDay(d + 1);
              time1.setLesson(time);
              //如果是体育这种没有teacherName的
              if (singleBr.length < 3) {
                course1.setCourseName(singleBr[0]);
                String[] addressAndWeek = singleBr[1].split(" ");
                boolean flag = true;
                for (int j = 0; j < addressAndWeek.length; j++) {
                  if (addressAndWeek[j].length() <= 1) {
                    continue;
                  }
                  if (addressAndWeek[j].length() > 1) {
                    if (flag) {
                      time1.setAddress(addressAndWeek[j]);
                      flag = false;
                    } else {
                      if (addressAndWeek[j].length() > 1) {
                        //第*-*周
                        if (addressAndWeek[j].contains("-")) {
                          String[] split = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1).split("-");
                          int n1 = Integer.parseInt(split[0]);
                          int n2 = Integer.parseInt(split[1]);
                          for (int i = n1; i <= n2; i++) {
                            time1.week.add(i);
                          }
                        }
                        //第*,*,*,*,*周
                        else if (addressAndWeek[j].contains(",")) {
                          String substring = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1);
                          String[] split = substring.split(",");
                          for (String s : split) {
                            int week = Integer.parseInt(s);
                            time1.week.add(week);
                          }
                        }
                        //第*周
                        else {
                          addressAndWeek[j] = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1);
                          int n = Integer.parseInt(addressAndWeek[j]);
                          time1.week.add(n);
                        }
                      }
                    }
                  }
                }
              } else {
                for (int k = 0; k < singleBr.length; k++) {
                  if (k == 0) {
                    course1.setCourseName(singleBr[k]);
                  } else if (k == 1) {
                    time1.setTeacher(singleBr[k]);
                  } else {
                    String[] addressAndWeek = singleBr[k].split(" ");
                    boolean flag = true;
                    for (int j = 0; j < addressAndWeek.length; j++) {
                      if (addressAndWeek[j].length() <= 1) {
                        continue;
                      }
                      if (addressAndWeek[j].length() > 1) {
                        if (flag) {
                          time1.setAddress(addressAndWeek[j]);
                          flag = false;
                        } else {
                          if (addressAndWeek[j].length() > 1) {
                            //第*-*周
                            if (addressAndWeek[j].contains("-")) {
                              String[] split = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1).split("-");
                              int n1 = Integer.parseInt(split[0]);
                              int n2 = Integer.parseInt(split[1]);
                              for (int i = n1; i <= n2; i++) {
                                time1.week.add(i);
                              }
                            }
                            //第*,*,*,*,*周
                            else if (addressAndWeek[j].contains(",")) {
                              String substring = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1);
                              String[] split = substring.split(",");
                              for (String s : split) {
                                int week = Integer.parseInt(s);
                                time1.week.add(week);
                              }
                            }
                            //第*周
                            else {
                              addressAndWeek[j] = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1);
                              int n = Integer.parseInt(addressAndWeek[j]);
                              time1.week.add(n);
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
              boolean isExist = false;
              for (Course item : courseList) {
                if (course1.getCourseName().equals(item.getCourseName())) {
                  isExist = true;
                  item.timeArrayList.add(time1);
                }
              }
              if (!isExist) {
                course1.timeArrayList.add(time1);
                courseList.add(course1);
              }
            }
          }
        }
      }
      time++;
    }
    return courseList;
  }


  /**
   * 获取个人课表
   *
   * @param username 用户名
   * @param password 密码
   */
  public static ScheduleResult getHbutPersonalSchedule(String username, String password)
      throws IOException, PasswordErrorException {
    ScheduleResult result = new ScheduleResult();
    Document document = HbutLoginUtil.getScheduleDoc(username, password);
    Elements h2 = document.select("h2");
    String title = h2.select("span").html();
    result.setTitle(title);
    Elements tr = document.select("tr");
    ArrayList<Course> courseList = new ArrayList<>(20);
    int time = 0;
    //time表示节段 time=1表示第1-2节
    for (Element element : tr) {
      if (time >= 1 && time <= 5) {
        Elements td = element.select("td");
        String[] day = String.valueOf(td).split("\n");
        //d表示周几
        for (int d = 0; d < day.length; d++) {
          if (day[d].contains("<br><br>")) {
            day[d] = day[d].substring(18, day[d].length() - 6);
            String[] singleCourse = day[d].split("<br><br>");
            for (String course : singleCourse) {
              String[] singleBr = course.split("<br>");
              Course course1 = new Course();
              Time time1 = new Time();
              time1.setDay(d + 1);
              time1.setLesson(time);
              //如果是体育这种没有teacherName的
              if (singleBr.length < 3) {
                course1.setCourseName(singleBr[0]);
                String[] addressAndWeek = singleBr[1].split(" ");
                boolean flag = true;
                for (int j = 0; j < addressAndWeek.length; j++) {
                  if (addressAndWeek[j].length() <= 1) {
                    continue;
                  }
                  if (addressAndWeek[j].length() > 1) {
                    if (flag) {
                      time1.setAddress(addressAndWeek[j]);
                      flag = false;
                    } else {
                      if (addressAndWeek[j].length() > 1) {
                        //第*-*周
                        if (addressAndWeek[j].contains("-")) {
                          String[] split = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1).split("-");
                          int n1 = Integer.parseInt(split[0]);
                          int n2 = Integer.parseInt(split[1]);
                          for (int i = n1; i <= n2; i++) {
                            time1.week.add(i);
                          }
                        }
                        //第*,*,*,*,*周
                        else if (addressAndWeek[j].contains(",")) {
                          String substring = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1);
                          String[] split = substring.split(",");
                          for (String s : split) {
                            int week = Integer.parseInt(s);
                            time1.week.add(week);
                          }
                        }
                        //第*周
                        else {
                          addressAndWeek[j] = addressAndWeek[j].substring(1,
                              addressAndWeek[j].length() - 1);
                          int n = Integer.parseInt(addressAndWeek[j]);
                          time1.week.add(n);
                        }
                      }
                    }
                  }
                }
              } else {
                for (int k = 0; k < singleBr.length; k++) {
                  if (k == 0) {
                    course1.setCourseName(singleBr[k]);
                  } else if (k == 1) {
                    time1.setTeacher(singleBr[k]);
                  } else {
                    String[] addressAndWeek = singleBr[k].split(" ");
                    boolean flag = true;
                    for (int j = 0; j < addressAndWeek.length; j++) {
                      if (addressAndWeek[j].length() <= 1) {
                        continue;
                      }
                      if (addressAndWeek[j].length() > 1) {
                        if (flag) {
                          time1.setAddress(addressAndWeek[j]);
                          flag = false;
                        } else {
                          if (addressAndWeek[j].length() > 1) {
                            //第*-*周
                            if (addressAndWeek[j].contains("-")) {
                              String[] split = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1).split("-");
                              int n1 = Integer.parseInt(split[0]);
                              int n2 = Integer.parseInt(split[1]);
                              for (int i = n1; i <= n2; i++) {
                                time1.week.add(i);
                              }
                            }
                            //第*,*,*,*,*周
                            else if (addressAndWeek[j].contains(",")) {
                              String substring = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1);
                              String[] split = substring.split(",");
                              for (String s : split) {
                                int week = Integer.parseInt(s);
                                time1.week.add(week);
                              }
                            }
                            //第*周
                            else {
                              addressAndWeek[j] = addressAndWeek[j].substring(1,
                                  addressAndWeek[j].length() - 1);
                              int n = Integer.parseInt(addressAndWeek[j]);
                              time1.week.add(n);
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
              boolean isExist = false;
              for (Course item : courseList) {
                if (course1.getCourseName().equals(item.getCourseName())) {
                  isExist = true;
                  item.timeArrayList.add(time1);
                }
              }
              if (!isExist) {
                course1.timeArrayList.add(time1);
                courseList.add(course1);
              }
            }
          }
        }
      }
      time++;
    }
    result.setSchedule(courseList);
    return result;
  }


  /**
   * 获取个人信息
   */
  public static StudentInfo getStuInfo(String username, String password)
      throws PasswordErrorException, IOException, NotSupportException {
    Document document = HbutLoginUtil.getStuInfoDoc(username, password);
    if(!"".equals(document.select("p").html())){
      throw new NotSupportException();
    }
    Elements td = document.select("td");
    StudentInfo studentInfo = new StudentInfo(
        td.get(0).html(),
        td.get(1).html(),
        td.get(2).html(),
        td.get(4).html(),
        td.get(5).html(),
        td.get(6).html(),
        td.get(7).html()
    );
    return studentInfo;
  }


  public static List<String> getAllEmptyClassRoom() throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getAllClassRoomDoc();
    List<String> classRoomList = new ArrayList<>(500);
    Elements classRooms = document.getElementsByClass("t-link t-in");
    for (Element item : classRooms) {
      String classRoom = item.html();
      try {
        int buildingId = Integer.parseInt(classRoom.substring(0, 1));
        if (buildingId != 6) {
          classRoomList.add(classRoom);
        }
      } catch (Exception e) {

      }
    }
    return classRoomList;
  }

  public static List<Classroom> getAllClassRoom() throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getAllClassRoomDoc();
    List<Classroom> classRoomList = new ArrayList<>(1500);
    Elements classRooms = document.getElementsByClass("t-link t-in");
    for (Element classroom : classRooms) {
      String classroomName=classroom.html();
      Element parent = classroom.parent();
      while ("".equals(parent.select("span").html())){
        parent=parent.parent();
      }
      String buildingName=parent.select("span").text();
      classRoomList.add(new Classroom(classroomName,buildingName));
    }
    return classRoomList;
  }



  /**
   * 获取全校所有班级名
   */
  public static List<ClassInfo> getAllClass() throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getAllClassDoc();
    List<ClassInfo> classInfoList = new ArrayList<>(300);
    Elements elementsByClass = document.getElementsByClass("t-group t-treeview-lines");
    Elements elements = elementsByClass.select("a");
    Elements lis = elementsByClass.select("li");
    Set<String> set = new HashSet<>();
    for (Element li : lis) {
      Elements spans = li.getElementsByClass("t-in");
      String college = spans.get(0).html();
      String judge = college.substring(college.length() - 1);
      if (!("院".equals(judge) || "处".equals(judge))) {
        continue;
      }
      Elements names = spans.select("a");
      for (Element a : names) {
        String name = a.html();
        if (set.contains(name)) {
          continue;
        }
        set.add(name);
        ClassInfo classInfo = new ClassInfo();
        classInfo.setCollegeName(college);
        classInfo.setGrade(name.substring(0, 2));
        classInfo.setClassName(name);
        classInfoList.add(classInfo);
      }
    }
    return classInfoList;
  }

  /**
   * 获取班级对应学院
   */
  public static String getClassCollege(String className)
      throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getAllClassDoc();
    Elements elementsByClass = document.getElementsByClass("t-group t-treeview-lines");
    Elements lis = elementsByClass.select("li");
    for (Element li : lis) {
      Elements spans = li.getElementsByClass("t-in");
      String college = spans.get(0).html();
      System.out.println(college);
      Elements names = spans.select("a");
      for (Element a : names) {
        if (a.html().equals(className)) {
          return college;
        }
      }
    }
    return null;
  }

  /**
   * 获取湖北工业大学工程技术学院课表
   */
  public static ScheduleResult getHbutEtcSchedule(String username, String password,
      String className)
      throws IOException, PasswordErrorException {
    String url = "http://202.114.190.75/student/courseSelect/thisSemesterCurriculum/ajaxStudentSchedule/callback";
    HttpPost httpPost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).build();
    httpPost.setConfig(requestConfig);
    httpPost.setHeader("User-Agent",
        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
    Map<String, Object> map;
    Gson gson = new Gson();
    CloseableHttpClient httpClient = HbutEtcLoginUtil.login(username, password);
    CloseableHttpResponse response = httpClient.execute(httpPost);
    log.info(LogUtil.getMessage(response.getStatusLine().getStatusCode() + ""));
    String s = EntityUtils.toString(response.getEntity(), "utf-8");
    log.info(LogUtil.getMessage("response:" + s));
    JSONObject jsonObject = JSONObject.fromObject(s);
    String xkxx = jsonObject.getString("xkxx");
    String substring1 = xkxx.substring(1, xkxx.length() - 1);
    String xkxx1 = "{" + "\"xkxx\": " + substring1 + "}";
    JSONObject jsonObject1 = JSONObject.fromObject(xkxx1);
    String xkxx2 = jsonObject1.getString("xkxx");

    map = gson.fromJson(xkxx2, Map.class);

    ArrayList<Course> courseList = new ArrayList<>(1);

    for (Map.Entry<String, Object> entry : map.entrySet()) {
      JSONObject jsonObject2 = JSONObject.fromObject(xkxx2);
      String course = jsonObject2.getString(entry.getKey());

      JSONObject jsonObject3 = JSONObject.fromObject(course);

      Object attendClassTeacher = jsonObject3.get("attendClassTeacher");
      if (attendClassTeacher.toString().length() == 0) {
        continue;
      }

      //将课程老师保存
      String teacher = attendClassTeacher.toString();

      //将课程名存入
      Object courseName = jsonObject3.get("courseName");
      String CourseName = courseName.toString();

      Object timeAndPlaceList = jsonObject3.get("timeAndPlaceList");
      String s1 = timeAndPlaceList.toString();
      if (s1.length() <= 2) {
        continue;
      }

      TimeAndPlaceList[] timeAndPlaceLists = gson.fromJson(s1, TimeAndPlaceList[].class);
      for (int i = 0; i < timeAndPlaceLists.length; i++) {
        Time time = new Time();
        //将授课老师存入
        time.setTeacher(teacher);
        Course course1 = new Course();
        //将课程名存入
        course1.setCourseName(CourseName);
        ArrayList<Time> timeList = new ArrayList<>(1);
        //设置星期几
        time.setDay(timeAndPlaceLists[i].classDay);

        String weekString = timeAndPlaceLists[i].weekDescription;

        //处理周数的字符串
        if (weekString.contains("双")) {
          int begin = Integer.parseInt(weekString.substring(0, weekString.lastIndexOf("-")));
          int end = Integer.parseInt(
              weekString.substring(weekString.lastIndexOf("-") + 1, weekString.lastIndexOf("周")));
          for (int j = begin; j <= end; ++j) {
            if (j % 2 == 0) {
              time.week.add(j);
            }
          }
        } else if (weekString.contains(",")) {
          String[] split = weekString.split(",");
          for (String weekString1 : split) {
            if (weekString1.contains("-")) {
              int begin, end;
              String[] split1 = weekString1.split("-");
              begin = Integer.parseInt(split1[0]);
              if (split1[1].contains("周")) {
                end = Integer.parseInt(split1[1].substring(0, split1[1].lastIndexOf("周")));
              } else {
                end = Integer.parseInt(split1[1]);
              }
              for (int j = begin; j <= end; ++j) {
                time.week.add(j);
              }
            } else if (weekString1.contains("周")) {
              int week = Integer.parseInt(weekString1.substring(0, weekString1.lastIndexOf("周")));
              time.week.add(week);

            } else {
              time.week.add(Integer.parseInt(weekString1));
            }
          }
        } else if (weekString.contains("-")) {
          int begin = Integer.parseInt(weekString.substring(0, weekString.lastIndexOf("-")));
          int end = Integer.parseInt(
              weekString.substring(weekString.lastIndexOf("-") + 1, weekString.lastIndexOf("周")));
          for (int j = begin; j <= end; ++j) {
            time.week.add(j);
          }
        } else {
          String substring = weekString.substring(1, weekString.length() - 1);
          int week = Integer.parseInt(substring);
          time.week.add(week);
        }

        //添加教学地址
        time.setAddress(timeAndPlaceLists[i].classroomName);

        //如果是连续的两节课
        if (timeAndPlaceLists[i].continuingSession > 2) {
          time.setLesson((timeAndPlaceLists[i].classSessions + 1) / 2);
          timeList.add(time);

          Time time1 = new Time();
          time1.setTeacher(time.getTeacher());
          time1.setDay(time.getDay());
          time1.setWeek(time.getWeek());
          time1.setAddress(time.getAddress());
          time1.setLesson(((timeAndPlaceLists[i].classSessions + 1) / 2) + 1);
          timeList.add(time1);

          course1.setTimeArrayList(timeList);
          courseList.add(course1);
        } else {
          //不是连续的两节课
          time.setLesson((timeAndPlaceLists[i].classSessions + 1) / 2);
          timeList.add(time);
          course1.setTimeArrayList(timeList);
          courseList.add(course1);
        }
      }


    }
    ScheduleResult result = new ScheduleResult(className, courseList,
        new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
    return result;
  }

  /**
   * 获取教室空闲时间
   */
  public static int[][][] getClassRoomEmptyTime(String classRoom)
      throws PasswordErrorException, IOException {
    int[][][] emptyTime = new int[28][8][6];
    for (int i = 0; i < 28; i++) {
      for (int j = 0; j < 8; j++) {
        for (int k = 0; k < 6; k++) {
          emptyTime[i][j][k] = 1;
        }
      }
    }
    Document document = HbutLoginUtil.getPlaceScheduleDoc(classRoom);
    Elements lessons = document.select("tr");
    for (int lesson = 1; lesson <= 5; lesson++) {
      Elements days = lessons.get(lesson).select("td");
      for (int day = 0; day < 7; day++) {
        String[] finalDatas = days.get(day).html().split("<br>");
        for (String finalData : finalDatas) {
          if (finalData.contains("|") && finalData.contains("周")) {
            String weekString = finalData.substring(finalData.lastIndexOf('|') + 2,
                finalData.lastIndexOf('周') + 1);
            String[] splitWeek = weekString.split(" ");
            for (String s : splitWeek) {
              if (s.contains("-")) {
                int begin = Integer.parseInt(s.substring(1, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length() - 1));
                for (int i = begin; i <= end; i++) {
                  emptyTime[i][day + 1][lesson] = 0;
                }
              } else if (s.contains(",")) {
                s = s.substring(1, s.length() - 1);
                String[] weeks = s.split(",");
                for (String item : weeks) {
                  int week = Integer.parseInt(item);
                  emptyTime[week][day + 1][lesson] = 0;
                }
              } else {
                int week = Integer.parseInt(s.substring(1, s.length() - 1));
                emptyTime[week][day + 1][lesson] = 0;
              }
            }
          }
        }
      }
    }
    return emptyTime;
  }

  /**
   *  获取老师的课程数据
   */
  public static void getTeacherCourse(String classroom) throws PasswordErrorException, IOException {
    Document document = HbutLoginUtil.getPlaceScheduleDoc(classroom);
    Elements lessons = document.select("tr");
    for (int lesson = 1; lesson <= 5; lesson++) {
      Elements days = lessons.get(lesson).select("td");
      for (int day = 0; day < 7; day++) {
        String[] finalDatas = days.get(day).html().split("<br>");
        for (String finalData : finalDatas) {
          System.out.println(finalData);
          if (finalData.length() > 0) {
            String[] split = finalData.split("\\|");
            String courseName = split[0].trim();
            if (courseName.length() > 1) {
              courseName = courseName.substring(1);
            }
            String classes = split[1].trim();
            String teacher = split[2].trim();
            if (teacher.length() > 0) {
              teacher = teacher.substring(0, teacher.indexOf("-"));
            }
            String weeks = split[3].trim();
            String[] classList = classes.split(",");
            String classJson = GSON.toJson(classList);
            Set<Integer> weeksList = new HashSet<>(32);
            String[] splitWeek = weeks.split(" ");

            for (String s : splitWeek) {
              System.out.println(s);
              if (s.contains("-")) {
                int begin = Integer.parseInt(s.substring(1, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length() - 1));
                for (int i = begin; i <= end; i++) {
                  weeksList.add(i);
                }
              } else if (s.contains(",")) {
                s = s.substring(1, s.length() - 1);
                String[] weekSplit = s.split(",");
                for (String item : weekSplit) {
                  int week = Integer.parseInt(item);
                  weeksList.add(week);
                }
              } else if (s.length() > 1) {
                int week = Integer.parseInt(s.substring(1, s.length() - 1));
                weeksList.add(week);
              }
            }
            String weeksJson = GSON.toJson(weeksList);
            if (teacher.length() > 0) {
              System.out.println(classJson);
              managerDao.insertTeacherCourse(teacher, courseName, classJson, weeksJson, day + 1,
                  lesson, classroom);
            }
          }
        }
      }
    }
  }


  private static int getDay(String dayString) throws Exception {
    switch (dayString){
      case "一":
        return 1;
      case "二":
        return 2;
      case "三":
        return 3;
      case "四":
        return 4;
      case "五":
        return 5;
      case "六":
        return 6;
      case "天":
        return 7;
      case "日":
        return 7;
      default:
        throw new Exception("dayString error");
    }
  }

  private static Set<Integer> getWeekSet(String weekString){
    Set<Integer> weeks=new HashSet<>(20);
    int begin=Integer.parseInt(weekString.substring(0,weekString.indexOf("-")));
    int end=Integer.parseInt(weekString.substring(weekString.indexOf("-")+1));
    for (int i=begin;i<=end;i++){
      weeks.add(i);
    }
    return weeks;
  }

  private static int getLesson(String lessonString) throws Exception {
    switch (lessonString){
      case "12":
        return 1;
      case "34":
        return 2;
      case "56":
        return 3;
      case "78":
        return 4;
      case "910":
        return 5;
      default:
        throw new Exception("lessonString error");
    }
  }

  public static ArrayList<OptionalCourse> getArbitrarilyCourse(String username,String password)
      throws Exception {
    ArrayList<OptionalCourse> optionalCourses=new ArrayList<>(2);
    Document document = HbutLoginUtil.getArbitrarilyCourseDoc(username, password);
    Elements formDelete = document.getElementsByAttributeValue("id","formDelete");
    Elements trs = formDelete.select("tr");
    for (int i=1;i< trs.size();i++){
      Element tr = trs.get(i);
      Elements td = tr.select("td");
      if(td.size()==10){
        String courseName = td.get(3).text();
        String timeAndAddress = td.get(9).text();
        String[] s = timeAndAddress.split(" ");
        String address=s[0];
        String weekString=s[1];
        String dayString=s[2];
        String lessonSting=s[3];
        int day=getDay(dayString.substring(2));
        Set<Integer> weeks=getWeekSet(weekString.substring(0,weekString.length()-1));
        int lesson=getLesson(lessonSting.substring(0,lessonSting.length()-1));
        OptionalCourse optionalCourse = new OptionalCourse();
        optionalCourse.setCourseName(courseName);
        optionalCourse.setAddress(address);
        optionalCourse.setWeeks(GSON.toJson(weeks));
        optionalCourse.setDay(day);
        optionalCourse.setLesson(lesson);
        optionalCourses.add(optionalCourse);
      }
    }
    return optionalCourses;
  }






}
